<?php

namespace Morrow;

class PageController extends DefaultController {
	public function run() {

		$this->form->loadDef(
			array('myform' => array(

		            "title" => array(
		            	"type" => "text",
		            	"required" => true,
    
	            	),

	            	"content" => array(
		            	"type" => "textarea",

	            	),
            	)
            )
        );

		$wid = $this->input->get('wid');

		if(!$wid){
			$this -> url -> redirect('home');
		}

		//var_dump($wid);

		if(!$this->session->get("uid")){
			$this -> url -> redirect('home');
		}

		$uid=$this->session->get('uid');
		//var_dump($uid);
		$this->load('Db', $this->config->get('db'));	

		$sql=$this->db->result('
			SELECT *
			FROM webapps
			WHERE uid = ? AND wid = ?'
			, array($uid,$wid));

		$result=$sql["RESULT"];

		if(count($result)==0){
			$this -> url -> redirect('user');
		}
		//var_dump($result);

		else{
			
			$this->view->setContent($sql, 'data');

		}	

		#define wid again for db
		//$wid =$result[0]['wid'];


		$this->form->setInput($this->input->get());

		if($this -> form -> isSubmitted('myform')) {
    			$valid = $this -> form -> validate('myform');

            	$this->view->setContent($this->form->getErrors('myform'), "error");

    				if ($valid) {
        		        $formdata = $this -> form -> getValues('myform');
        				
                        $this->load('db', $this->config->get('db'));

                        $now = date("Y-m-d H:i:s",time());
                        $add_time = array('add_time'=> $now);
        				$data_add_add_time=array_merge($formdata, $add_time);

        				$this->db->updateSafe('webapps', $data_add_add_time, 'where wid = ?', true, $wid);

        				//set messenger

        				$this->session->set('messenger', 'edit1');
        				
	        			//var_dump($data);
	        			$this -> url -> redirect('edit');

    				} 
    				else {
    				}
		}		
		
	}
}